import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Image, Textarea } from '@tarojs/components';
import './index.scss';

import { useUserInfo } from '@/hooks/useUserInfo';
import { requestUploadFile } from '@/utils/common';
import apiRequest from '@/service/apiRequest';
import { useDispatch } from 'react-redux';
import { updateSelectedIndex } from '@/actions/footerBar';
import IconFont from '@/components/iconfont';

const FOOTER_BAR_MENU_LIST: any[] = [
  { icon: "pet-tupian", label: "图片", iconColor: "#333333", type: "" },
  { icon: "pet-zhaoxiangji", label: "拍摄", iconColor: "#333333", type: "camera" },
]

const MAX_IMAGE_COUNT = 3;

function PostPage() {
  const { userInfo } = useUserInfo();
  const dispatch = useDispatch();
  const [content, setContent] = useState<string>('');
  // const [selectedTags, setSelectedTags] = useState(['柴犬', '狗狗日常']);
  // "https://hlwyy.9yiban.com/hosinfo108/static108/home_top_view_no_text.jpg"
  const [images, setImages] = useState<any>([]);
  const [footerBarStyle, setFooterBarStyle] = useState<any>({})
  // 添加标签
  // const handleTagClick = (tag) => {
  //   if (selectedTags.includes(tag)) {
  //     setSelectedTags(selectedTags.filter(t => t !== tag));
  //   } else {
  //     setSelectedTags([...selectedTags, tag]);
  //   }
  // };

  // 监听键盘高度变化
  useEffect(() => {
    const keyboardShowListener: any = Taro.onKeyboardHeightChange(res => {
      let class_style = res.height > 0 ? {
        bottom: `${res.height}px`,
        paddingBottom: '0px'
      } : {
        bottom: '0px'
      };
      setFooterBarStyle(class_style);
    });
    
    return () => {
      // 组件卸载时移除监听
      keyboardShowListener && keyboardShowListener.stop && keyboardShowListener.stop();
    };
  }, []);
  
  // 选择图片
  const chooseImage = (sourceType: any = ['album', 'camera']) => {
    Taro.chooseImage({
      count: MAX_IMAGE_COUNT - images.length,
      sizeType: ['compressed'],
      sourceType,
      success: async (res) => {
        // let requestList = res.tempFilePaths.map(item => () => requestUploadFile(item, `${userInfo.pid}_posts_${item.substring(item.lastIndexOf('/')+1)}`))
        // let uploadResult = await Promise.all(requestList.map(item => item()));
        // console.log(uploadResult, "uploadResult===");
        // if (uploadResult) {
        //   setImages([...images, ...uploadResult.map((item: any) => item.data)]);
        // }
        setImages([...images, ...res.tempFilePaths]);
      }
    });
  };
  
  // 删除图片
  const removeImage = async (index) => {
    // let res = await apiRequest.post("/api/upload_files/remove", {
    //   pet_upload_file: images[index]
    // });
    // if (res.result) {
      let newImages = [...images];
      newImages.splice(index, 1);
      setImages(newImages);
    // }
  };
  
  // 发布动态
  const handleSubmit = async () => {
    if (!content.trim() && images.length === 0) {
      Taro.showToast({
        title: '请输入内容或上传图片',
        icon: 'none'
      });
      return;
    }
    let params = {
      userId: userInfo.userId,
      content,
      images,
    }
    if (images && images.length > 0) {
      let requestList = images.map(item => () => requestUploadFile(item, `${userInfo.pid}_posts_${item.substring(item.lastIndexOf('/')+1)}`))
      let uploadResultList = await Promise.allSettled(requestList.map(item => item()));
      params.images = uploadResultList.filter(item => item.status === 'fulfilled').map((item: any) => item.value.data);
    }

    let res = await apiRequest.post("/api/posts", params);
    if (res.result) {
      Taro.showToast({
        title: '发布成功',
        icon: 'success',
        duration: 2000,
        success: () => {
          handleNavigateBack();
        }
      });
    }
  };

  const handleNavigateBack = () => {
    dispatch(updateSelectedIndex(0));
    Taro.reLaunch({
      url: '/homeIndex/pages/home/index'
    });
  };

  const handleSelectImgType = (item) => {
    if (images.length >= MAX_IMAGE_COUNT) {
      return
    }
    chooseImage(item.type === "camera" ? ['camera'] : ['camera', 'album'])
  }

  const handlePreviewImage = (index) => {
    Taro.previewImage({
      current: images[index],
      urls: images,
    })
  }

  const handleRemoveImage = (event, index) => {
    event.stopPropagation();
    removeImage(index); 
  }

  // 渲染
  const renderFooterBarMenus: any = FOOTER_BAR_MENU_LIST.map((item, index) => (
    <View className={images.length >= MAX_IMAGE_COUNT ? 'tool-item over-tool-item' : 'tool-item'} key={index} onClick={() => handleSelectImgType(item)}>
      {/* <AtIcon value={item.type} size='32' color={item.iconColor}></AtIcon> */}
      <IconFont name={item.icon} color={item.iconColor} size={50} />
    </View>
  ));

  return (
    <View className='post-container'>
      <View className='posts-header-box'>
        <View className='flex-c-c title'>发布动态</View>
        <View className='action-box flex-b-c'>
          <View onClick={handleNavigateBack}>取消</View>
          <View className='send-btn' onClick={handleSubmit}>发送</View>
        </View>
      </View>
      {/* 内容输入区 */}
      <View className='content-area'>
        <Textarea
          className='content-input'
          placeholder='分享您的宠物趣事...'
          value={content}
          onInput={(e) => setContent(e.detail.value)}
          maxlength={500}
          autoFocus={true}
          showConfirmBar={false}
          adjustPosition={true}
          disableDefaultPadding={true}
        />
      </View>
      
      {/* 标签区域 */}
      {/* <View className='tags-area'>
        {selectedTags.map((tag, index) => (
          <View key={index} className='tag-item'>
            <AtTag 
              name={tag}
              active
              circle
              onClick={() => handleTagClick(tag)}
            >
              #{tag}
            </AtTag>
          </View>
        ))}
        <View className='add-tag'>
          <Text>添加标签...</Text>
        </View>
      </View> */}
      
      {/* 图片区域 */}
      <View className={images.length ? 'images-area-border images-area' : 'images-area'}>
        {images.map((img, index) => (
          <View key={`${img}-${index}`} className='posts-image-item image-item flex-c-c' onClick={() => handlePreviewImage(index)}>
            <Image src={img} mode='aspectFill' webp />
            <View className='delete-icon' onClick={(event) => handleRemoveImage(event, index)}>×</View>
          </View>
        ))}
        {
          (images.length >= 1 && images.length < MAX_IMAGE_COUNT) ? (
            <View className='posts-image-item add-image' onClick={() => chooseImage()}>
              <Text className='add-icon'>+</Text>
              <Text className='add-text'>添加图片</Text>
            </View>
          ) : null
        }
      </View>
      
      {/* 底部工具栏 */}
      <View className="footer-bar-wrapper" style={footerBarStyle}>
        <View className='footer-toolbar flex-a-c'>
          { renderFooterBarMenus }
        </View>
      </View>
    </View>
  );
}

export default PostPage;
